<template>
  <div class="goods-add">
    <!-- 1.面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2.卡片 -->
    <el-card>
      <!-- 2.1 提示条 -->
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>
      <!-- 2.2 步骤 -->
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 2.3 tabs -->
      <el-form
        :model="goodsAddForm"
        :rules="goodsAddRules"
        ref="goodsAddRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          tab-position="left"
          :before-leave="handleBeforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsAddForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsAddForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsAddForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsAddForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="goodsAddForm.goods_cat"
                :options="categoryList"
                :props="categoryProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 版式 -->
            <el-form-item
              v-for="item in manyData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(subitem, subindex) in item.attr_vals"
                  :key="subindex"
                  :label="subitem"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyData"
              :label="item.attr_name"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture"
              :headers="uploadToken"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor
              v-model="goodsAddForm.goods_introduce"
              ref="myQuillEditor"
            ></quill-editor>

            <el-button
              type="primary"
              style="margin-top: 15px;"
              @click="handleGoodsAdd"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览弹出层 -->
    <el-dialog title="图片预览" :visible.sync="imagePreviewDialog" width="30%">
      <img width="100%" :src="imagePreviewPath" alt />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // tabs的名字
      activeName: "0",
      // 表单数据对象
      goodsAddForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      // 表单校验对象
      goodsAddRules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称!",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            message: "请输入商品名称!",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            message: "请输入商品名称!",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "请输入商品名称!",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            message: "请输入商品名称!",
            trigger: "blur"
          }
        ]
      },
      // 分类列表
      categoryList: [],
      // 分类列表配置对象
      categoryProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      manyData: [],
      onlyData: [],
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      uploadToken: {
        Authorization: window.sessionStorage.getItem("token")
      },
      imagePreviewDialog: false,
      imagePreviewPath: ""
    };
  },
  methods: {
    // 当复选框有没有被选中的时候 看看数组中选中过的值
    // handleChecked() {
    //   console.log(this.manyData);
    // },
    // tab切换的时候触发
    async handleClick() {
      // 判断 this.activeName是不是1 如果是1 获取动态参数
      if (this.activeName == 1) {
        const { data: res } = await this.$http.get(
          `categories/${this.categoryId}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );

        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数数据失败");
        }

        // 用空格把数据分开
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.trim().split(" ");
        });

        console.log(res);
        this.manyData = res.data;
      } else if (this.activeName == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.categoryId}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );

        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数数据失败");
        }

        this.onlyData = res.data;
      }
    },
    // 当级联列表中的值发生变化的时候触发
    handleChange() {
      // 如果选中项的数组的长度不为三 直接让数组为空
      if (this.goodsAddForm.goods_cat.length !== 3) {
        this.goodsAddForm.goods_cat = [];
      }
    },
    // 图片预览
    handlePreview(file) {
      // console.log("111");
      this.imagePreviewPath = file.response.data.url;
      this.imagePreviewDialog = true;
    },
    // 图片删除
    handleRemove(file) {
      // console.log(file);
      let path = file.response.data.tmp_path;
      let i = this.goodsAddForm.pics.findIndex(item => item.pic == path);
      // console.log(i);
      this.goodsAddForm.pics.splice(i, 1);
      console.log(this.goodsAddForm);
    },
    // 图片上传成功时的回调
    // eslint-disable-next-line no-unused-vars
    handleSuccess(response, file, fileList) {
      // console.log(response);
      // 当图片上传成功
      // const o =
      this.goodsAddForm.pics.push({
        pic: response.data.tmp_path
      });

      // console.log(this.goodsAddForm);
    },
    // 判断是否可以从第一个标签跳转到其他标签
    // 是不是第一个标签(activeName 0) 并且是不是已经选中了第三级分类(判断有没有分类id)
    // current代表当前
    // prev是马上要离开的标签页的名字
    // handleError(error) {
    //   console.log(error);
    // },
    // eslint-disable-next-line no-unused-vars
    handleBeforeLeave(next, prev) {
      // console.log(next, prev);
      // 如果prev是0 且没有分类id 那么就不让跳转 直接return false
      if (this.activeName == 0 && this.categoryId == null) {
        this.$message.error("请选中三级分类");
        return false;
      }
      // 如果是0也有分类id 就啥都不干 放行
    },
    handleGoodsAdd() {
      this.$refs.goodsAddRef.validate(async valid => {
        if (!valid) return this.$message.error("请把数据填写完整");
        // console.log(this.goodsAddForm);

        const form = _.cloneDeep(this.goodsAddForm);
        console.log(form);

        //  把商品分类 数组变成字符串
        form.goods_cat = form.goods_cat.join(",");

        // 把manyData中的数据添加到attrs中
        // console.log("================");
        // console.log(this.manyData);
        this.manyData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(" ")
          });
        });
        // 把onlyData中的数据添加到attr中去
        this.onlyData.forEach(item => {
          form.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          });
        });

        const { data: res } = await this.$http
          .post("goods", form)
          .catch(error => error);

        // console.log(res);
        if (res.meta.status == 400) {
          return this.$message.error(res.meta.msg);
        }

        this.$message.success("商品创建成功");
        this.$router.push("/goods");
      });
    },

    async getCategoryList() {
      const { data: res } = await this.$http.get("categories");

      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败");
      }
      // 给分类列表赋值
      this.categoryList = res.data;
    }
  },
  created: function() {
    this.getCategoryList();
  },
  computed: {
    categoryId: function() {
      if (this.goodsAddForm.goods_cat.length === 3) {
        return this.goodsAddForm.goods_cat[2];
      }
      return null;
    }
  }
};
</script>
<style>
.el-steps,
.el-tabs,
.el-card {
  margin-top: 25px;
}

.ql-editor {
  min-height: 400px;
}
</style>
